import requests
import json

class WechatPushTool:

    def __init__(self):
        self.corpid = "ww54dade3183d04c38"
        self.corpsecret = "p8O6NkxPGG4jux8OSn9zQuhbBAieh1pwr4ceiM1XufQ"
        self.agentid = "1000002"
        self.access_token = self.get_access_token()

    def get_access_token(self):
        url = f'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={self.corpid}&corpsecret={self.corpsecret}'
        try:
            response = requests.get(url)
            response.raise_for_status()
            result = response.json()
            if result.get('errcode') == 0:
                return result.get('access_token')
            else:
                print(f'获取access_token失败，错误码: {result.get("errcode")}, 错误信息: {result.get("errmsg")}')
        except requests.RequestException as e:
            print(f'请求出错: {e}')
        return None

    def push_message(self, user, message):
        if not self.access_token:
            print('未获取到有效的access_token，无法推送消息。')
            return
        url = f'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={self.access_token}'
        data = {
            "touser": user,
            "msgtype": "text",
            "agentid": self.agentid,
            "text": {
                "content": message
            },
            "safe": 0
        }
        try:
            response = requests.post(url, data=json.dumps(data))
            response.raise_for_status()
            result = response.json()
            if result.get('errcode') == 0:
                print('消息推送成功。')
            else:
                print(f'消息推送失败，错误码: {result.get("errcode")}, 错误信息: {result.get("errmsg")}')
        except requests.RequestException as e:
            print(f'请求出错: {e}')

if __name__ == '__main__':
    # 使用示例，需要替换为实际的企业微信信息

    user = "YinQi"
    message = "这又是一条测试消息。"
    push_tool = WechatPushTool()
    push_tool.push_message(user, message)